package com.hydong.tvdemo

import android.os.Bundle
import android.view.*
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class MainActivity : BaseActivity() {
    var tvTitle: TextView? = null
    var mProgressBar: ProgressBar? = null
    var mWebView: WebView? = null
    val webUrl = "https://www.baidu.com/s?wd=免费看电视剧"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        tvTitle = findViewById(R.id.tv_title)
        mProgressBar = findViewById(R.id.progress_bar)
        mWebView = findViewById(R.id.web_view)

        mWebView?.also {
            // 修改 webview 尺寸，可以避免因弹框导致的页面局部放大
            val display = windowManager.defaultDisplay
            var lp = it.layoutParams
            lp.width = display.width
            lp.height = display.height
            it.layoutParams = lp

            // 初始化 webview 参数
            it.settings.javaScriptEnabled = true
            it.settings.userAgentString = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
            it.settings.setSupportZoom(true)
            it.settings.builtInZoomControls = true
            it.settings.useWideViewPort = true
            it.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            it.settings.loadWithOverviewMode = true

            it.settings.domStorageEnabled = true
            it.settings.cacheMode = WebSettings.LOAD_NO_CACHE

            val webViewClient: WebViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                    super.shouldOverrideUrlLoading(view, url)
                    view.loadUrl(url ?: "")
                    return true
                }
            }


            it.webViewClient = webViewClient

            var webChromeClient: WebChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView?, title: String?) {
                    super.onReceivedTitle(view, title)
                    tvTitle?.also { it.text = title }
                }

                override fun onProgressChanged(view: WebView?, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                    mProgressBar?.also {
                        if (newProgress == 0 || newProgress == 100) {
                            it.visibility = View.GONE
                        } else {
                            it.visibility = View.VISIBLE
                            it.progress = newProgress
                        }
                    }
                }
            }
            it.webChromeClient = webChromeClient

            it.loadUrl(webUrl)
        }
    }

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (mWebView?.canGoBack() == true) {
                    mWebView?.goBack()
                } else {
                    if ((System.currentTimeMillis() - exitTime) > 2000) {
                        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                        exitTime = System.currentTimeMillis()
                    } else {
                        finish();
                    }
                }
                return true
            }
            KeyEvent.KEYCODE_MENU -> {
                // 菜单键（Menu）
                mWebView?.reload() // 刷新
                return true
            }
//            KeyEvent.KEYCODE_DPAD_LEFT -> {
//                // 方向键『左』（Left）
//                mWebView?.goBack() // 后退
//                return true
//            }
//            KeyEvent.KEYCODE_DPAD_RIGHT -> {
//                // 方向键『左』（Left）
//                mWebView?.goForward() // 前进
//                return true
//            }
        }
        return super.onKeyDown(keyCode, event)
    }

}